package com.example.data.factory.service.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.data.factory.common.Dto.ClassifyBatchDto;
import com.example.data.factory.common.Dto.InserttaskDto;
import com.example.data.factory.common.Dto.SearchTaskDto;
import com.example.data.factory.common.Dto.UpdateTaskStatusDto;
import com.example.data.factory.common.common.StringConstant;
import com.example.data.factory.common.result.PageVO;
import com.example.data.factory.common.result.R;
import com.example.data.factory.common.util.CommonUtil;
import com.example.data.factory.entity.entity.Classify;
import com.example.data.factory.entity.entity.Task;
import com.example.data.factory.mapper.mapper.ClassifyMapper;
import com.example.data.factory.mapper.mapper.TaskMapper;
import com.example.data.factory.service.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lhy
 * @since 2025-03-03
 */
@Service
@RequiredArgsConstructor
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {
    private final CommonUtil commonUtil;
    private final ClassifyMapper classifyMapper;

    public String buildCategoryPath(Long id) {
        StringBuilder fullPath = new StringBuilder ();
        Classify currentCategory = classifyMapper.selectById ( id );

        // 递归向上查找直到根节点
        while (currentCategory != null) {
            if (fullPath.length () > 0) {
                fullPath.insert ( 0, "/" );
            }
            fullPath.insert ( 0, currentCategory.getName () );
            if (currentCategory.getParentId () != null && !currentCategory.getParentId ().equals ( 0L )) {
                currentCategory = classifyMapper.selectById ( currentCategory.getParentId () );
            } else {
                break;
            }
        }
        return fullPath.toString ();
    }

    @Override
    public R<Task> searchTask(SearchTaskDto searchTaskDto) {
        // 初始化分页对象
        Page<Task> page = new Page<> ( searchTaskDto.getPageNumber (), searchTaskDto.getPageSize () );

        // 构建查询条件
        LambdaQueryWrapper<Task> lambdaQueryWrapper = new LambdaQueryWrapper<Task> ()
                .like ( StringUtils.isNotBlank ( searchTaskDto.getTaskName () ), Task::getTaskName, searchTaskDto.getTaskName () )
                .eq ( searchTaskDto.getStatus () != null, Task::getStatus, searchTaskDto.getStatus () )
                .eq ( Task::getDeleted, 0 );
        // 执行分页查询
        Page<Task> pageResult = this.page ( page, lambdaQueryWrapper );
        if (pageResult.getRecords ().isEmpty ()) {
            return R.Failed ( StringConstant.SEARCHFAILD );
        }
        // 将分页结果转换为 VO 对象
        PageVO<Task> pageVO = new PageVO<> ();
        BeanUtil.copyProperties ( pageResult, pageVO );
        return R.Success ( pageVO );
    }

    @Override
    public R<Task> updatestatus(UpdateTaskStatusDto updateTaskStatusDto) {
        //判断输入的id是否存在
        List<Task> list = this.list ();
        Task task = new Task ();
        if (!(list.stream ().allMatch ( date -> date.getTaskId ().equals ( updateTaskStatusDto.getTaskId () ) ))) {
            return R.Failed ( "该id不存在" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<Task> ().set ( Task::getStatus, updateTaskStatusDto.getStatus () )
                .eq ( Task::getTaskId, updateTaskStatusDto.getTaskId () ) );
        if (update) {
            return R.Success ( StringConstant.UPDATESUCCESS );
        }
        task.setUpdateTime ( LocalDateTime.now () );
        return R.Failed ( StringConstant.UPDATEFAILED );
    }

    @Override
    public R<Task> updatestatusbash(List<UpdateTaskStatusDto> updateTaskStatusDtos) {
        //判断是否输入id集合
        if (updateTaskStatusDtos.isEmpty () || updateTaskStatusDtos == null) {
            return R.Failed ( "数据不存在" );
        }
        boolean allsuccess = true;
        for (UpdateTaskStatusDto dto : updateTaskStatusDtos) {
            Task one = this.getOne ( new LambdaQueryWrapper<Task> ().eq ( Task::getTaskId, dto.getTaskId () )
                    .eq ( Task::getDeleted, 0 ) );
            if (one == null) {
                allsuccess = false;
                continue;
            }
            Task task = new Task ();
            task.setUpdateTime ( LocalDateTime.now () );
            boolean update = this.update ( new LambdaUpdateWrapper<Task> ().set ( Task::getStatus, dto.getStatus () )
                    .eq ( Task::getTaskId, dto.getTaskId () ) );
            if (!update) {
                allsuccess = false;
            }
        }
        if (allsuccess) {
            return R.Success ( StringConstant.UPDATESUCCESS );
        } else {
            return R.Failed ( "部分更新失败，可能是由于某些字典项已被删除或更新条件不匹配" );
        }
    }

    @Override
    public R<Map<String, String>> classifybash(ClassifyBatchDto classifyBatchDto) {
        //解析请求参数
        List<String> taskNames = classifyBatchDto.getTaskName ();
        String categoryName = classifyBatchDto.getCategoryName ();
        if (taskNames == null || taskNames.isEmpty () || categoryName == null || categoryName.isEmpty ()) {
            return R.Failed ( "未输入有效的数据" );
        }
        Map<String, String> results = new HashMap<> ();
        Classify classify = classifyMapper.selectByname ( categoryName );
        if (classify == null) {
            for (String taskName : taskNames) {
                results.put ( taskName, "没有找到该分类" );
            }
            return R.Failed ( results.toString () );
        }
        //构建分类路径
        String s = buildCategoryPath ( Long.valueOf ( classify.getId () ) );
        for (String taskName : taskNames) {
            Task one = this.getOne ( new LambdaQueryWrapper<Task> ().eq ( Task::getTaskName, taskName ) );
            if (one == null) {
                results.put ( taskName, "任务不存在" );
                continue;
            }
            boolean update = this.update ( new LambdaUpdateWrapper<Task> ().set ( Task::getCategoryName, s )
                    .set ( Task::getClassifyId, classify.getId () )
                    .set ( Task::getUpdateTime, LocalDateTime.now () )
                    .eq ( Task::getTaskId, one.getTaskId () ) );
            if (!update) {
                return R.Failed ( StringConstant.UPDATEFAILED );
            } else {
                return R.Success ( StringConstant.UPDATESUCCESS );
            }
        }
        long successCount = results.values ().stream ().filter ( result -> results.equals ( "更新成功" ) ).count ();
        long failedCount = results.size () - successCount;
        if (failedCount > 0) {
            return R.Failed ( results.toString () );
        } else {
            return R.Success ( StringConstant.UPDATESUCCESS );
        }
    }

    @Override
    public R<Task> delete(Integer taskId) {
        List<Task> list = this.list ();
        if (!(list.stream ().anyMatch ( data -> data.getTaskId ().equals ( taskId ) ))) {
            return R.Failed ( "该id不存在" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<Task> ().set ( Task::getDeleted, 1 )
                .eq ( Task::getTaskId, taskId ) );
        if (update) {
            return R.Success ( StringConstant.UPDATESUCCESS );
        }
        return R.Failed ( StringConstant.UPDATEFAILED );
    }

    //新增任务基本信息接口
    @Override
    public R<Task> inserttask(InserttaskDto inserttaskDto, HttpServletRequest request) {
        //先获取分类名称
        String categoryName = inserttaskDto.getCategoryName ();
        if (categoryName == null || categoryName.isEmpty ()) {
            return R.Failed ( "无效的分类名称" );
        }
        try {
            Classify classify = classifyMapper.selectByname ( categoryName );
            if (classify == null || ObjectUtils.isEmpty ( classify )) {
                return R.Failed ( "该分类不存在" );
            }
            String categoryPath = buildCategoryPath ( Long.valueOf ( classify.getId () ) );
            Task task = new Task ();
            String s = commonUtil.extractUsernameFromRequest ( request );
            BeanUtil.copyProperties ( inserttaskDto, task );
            List<Task> list = this.list ();
            task.setUpdateTime ( LocalDateTime.now () );
            task.setCreateTime ( LocalDateTime.now () );
            task.setClassifyId ( classify.getId () );
            task.setCategoryName ( categoryPath );
            task.setCreateBy ( s );
            if (list.stream ().anyMatch ( data -> data.getTaskName ().equals ( inserttaskDto.getTaskName () ) )) {
                return R.Failed ( StringConstant.ERRO );
            }
            boolean save = this.save ( task );
            if (save) {
                return R.Success ( StringConstant.INSERTSUCCESS );
            } else {
                return R.Failed ( StringConstant.UPDATESUCCESS );
            }
        } catch (Exception e) {
            return R.Failed ( e.getMessage () );
        }
    }
    //新增节点信息配置
    //新增任务触发配置
    //一步到位全部新增接口
    //编辑接口
    //测试接口
}
